package com.app.Controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

import it.unipr.ce.dsg.s2p.message.Payload;
import it.unipr.ce.dsg.s2p.org.json.JSONException;
import it.unipr.ce.dsg.s2p.org.json.JSONObject;
import it.unipr.ce.dsg.s2p.sip.Address;

import ReadWriteXML.CMember;
import ReadWriteXML.ReadXML;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Intent;
import android.graphics.YuvImage;
import android.os.Handler;
import android.util.Log;

import com.app.Activity.frmBieuQuyetMoiRoiNhom;
import com.app.Activity.frmChatPeerActivity;
import com.app.Activity.frmMainActivity;
import com.app.Activity.frmMyConversation;
import com.app.Activity.frmTest;
import com.app.Activity.tabActivity;

import com.app.Activity.trucActivity;
import com.app.DTO.AccountDTO;
import com.app.DTO.RoleDTO;
import com.app.Message.PingMessage;
import com.app.Network.NetworkLayer;
import com.app.Network.Protocol;
import com.app.PhanQuyen.Quyen;
import com.app.Tree.INode;
import com.app.Tree.TextNode;


public class NetworkController {

	private static int nodeCurrenIndex = 0;
	public static NetworkLayer _peer = null;
	public static Handler handler = new Handler();
	public static Address sender;
	public static String thanhLapNhomIP="";
	// chat rieng
	private static boolean _isOffline = false;
	private static String _ipHost = null;
	private static String _ipUser;
	private static Runnable _runUpdateMsg;
	private static String _userName = null;
	private static String _fullName = "PTT TRUC";
	private static boolean isConnected=false;
	private static ArrayList<Address> Iponline = new ArrayList<Address>();
	private static String groupName = "";

	public static String getGroupName() {
		return groupName;
	}

	public static void setGroupName(String groupName) {
		NetworkController.groupName = groupName;
	}
	
	



	/**
	 * Phú Gửi lời mời vào nhóm
	 * 
	 * @param toAddress
	 *            : Địa chỉ muốn mời
	 * @param groupName
	 *            : Tên nhóm của mình
	 * @param msg
	 *            : Lời nhắn(mời)
	 * @return
	 */

	public static boolean sendGroupInvite(Address toAddress, String groupName, String msg) {

		Log.d("Phu", " vao ham sendGroupInvite: groupName:"+groupName+ " msg:"+msg);
		
			PingMessage message = new PingMessage(_peer.getPeerDescriptor());
			message.setType(Protocol.GROUP_INVITE);
			Payload payload = new Payload();
			payload.addParam(Protocol.GROUP_INVITE_DATA_GROUP_NAME, groupName);
			payload.addParam(Protocol.GROUP_INVITE_DATA_MSG, msg);
			message.setPayload(payload);
			_peer.send(toAddress, message);
			Log.d("Phu", "Da send sendGroupInvite to: " + toAddress.getHost() + ":" + toAddress.getPort());
		
		return true;
	}

	public static boolean sendDongYVaoNhom(Address toAddress) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.GROUP_INVITE_REPLY_YES);
		_peer.send(new Address(toAddress), msg);
		Log.d("Phu", "Da send sendDongYVaoNhom to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendKhongChoVaoNhom(Address toAddress) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.GROUP_INVITE_NO);
		_peer.send(new Address(toAddress), msg);
		Log.d("Phu", "Da send sendKhongChoVaoNhom to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendChoVaoNhom(Address toAddress) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.GROUP_INVITE_YES);
		_peer.send(new Address(toAddress), msg);
		Log.d("Phu", "Da send sendChoVaoNhom to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;

	}

	public static boolean sendSetRole(Address toAddress, ArrayList<RoleDTO> roleList) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());

		Payload payload = new Payload();
		payload.addParam("DATA", RoleDTO.toStringList(roleList));
		msg.setType(Protocol.SET_ROLE);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendSetRole to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendJoinGroup(Address toAddress, String userName, String fullName) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());

		Payload payload = new Payload();
		payload.addParam(Protocol.MEMBER_FULL_NAME, fullName);
		payload.addParam(Protocol.MEMBER_USER_NAME, userName);

		msg.setType(Protocol.JOIN_GROUP);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendJoinGroup to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendUpdateMember(Address toAddress, CMember member) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());

		Payload payload = new Payload();
		payload.addParam(Protocol.UPDATE_MEMBER_LIST, member.toParse());
		msg.setType(Protocol.UPDATE_MEMBER_LIST);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendUpdateMember to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendMemberList(Address toAddress, ArrayList<CMember> memberList) {

		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.MEMBER_LIST, CMember.toParseList(memberList));
		msg.setType(Protocol.MEMBER_LIST);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendMemberList to:" + toAddress.getHost() + ":" + toAddress.getPort() + "/data: "
				+ CMember.toParseList(memberList));
		return true;
	}

	public static boolean sendStartGroup(Address toAddress) {
		Log.d("Phu", "Da send sendMemberList to:" + toAddress.toString());
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.START_GROUP);
		_peer.send(toAddress, msg);
		return true;
	}

	public static boolean sendAddTreeNode(Address toAddress,long parentID, INode node) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.ADD_NODE, node.toParse());
		payload.addParam(Protocol.TREENODE_ID, parentID+"");
		msg.setType(Protocol.ADD_NODE);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("123", "Da send sendAddTreeNode to:" + toAddress.toString()+" parentID="+parentID);
		return true;
	}
	public static boolean sendUpdateNodeText(Address toAddress, INode node){
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.NODE_UPDATE, node.toParse());
		msg.setType(Protocol.UPDATE_NODE_TEXT);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendUpdateNodeText to:" + toAddress.toString());
		return true;
	}
	public static boolean sendDeleteTreeNode(Address toAddress, INode node){
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.DELETE_NODE_TREE,node.toParse());
		msg.setType(Protocol.DELETE_NODE_TREE);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendDeleteTreeNode to:" + toAddress.toString());
		return true;
		
	}
	public static ArrayList<CMember> getMemberList() {
		ArrayList<CMember> memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
		Log.d("Phu", "NetworkController. getMemberList size:" + memberList.size());
		return memberList;
	}

	public static boolean sendPing(Address toAddress){		
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.PING_MSG);
		_peer.send(toAddress, msg);
//		Log.d("PingThread","NetworkController-sendPing to: "+toAddress.toString());
		return true;
	}	
	public static boolean sendPingReply(Address toAddress){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.PING_MSG_REPLY);
		_peer.send(toAddress, msg);
//		Log.d("PingThread","NetworkController-sendPingReply to: "+toAddress.toString());
		return true;
	}
	public static boolean sendPingOnline(Address toAddress){		
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.PING_MSG_ONLINE);
		_peer.send(toAddress, msg);
		Log.d("PingThread","NetworkController-sendPing to: "+toAddress.toString());
		return true;
	}
	public static boolean sendPingReplyOnline(Address toAddress){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.PING_MSG_REPLY_ONLINE);
		_peer.send(toAddress, msg);
		Log.d("PingThread","NetworkController-sendPingReply to: "+toAddress.toString());
		return true;
	}
//	public static boolean sendNodeIFOnline(Address toAddress, long pID, INode node){		
//		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
//		Payload p = new Payload();
//		p.addParam("PID", String.valueOf(pID));
//		p.addParam("NODE", node.toParse());
//		msg.setType("SEND_NODE_IF_ONLINE");
//		msg.setPayload(p);
//		_peer.send(toAddress, msg);
//		Log.d("PingThread","NetworkController-sendPing to: "+toAddress.toString());
//		return true;
//	}
//	public static boolean sendNodeReplyOnline(Address toAddress, String pID, String newnode){
//		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
//		Payload p = new Payload();
//		p.addParam("PID", pID);
//		p.addParam("NEWNODE", newnode);
//		msg.setType("SEND_NODE_REPLY");
//		msg.setPayload(p);
//		_peer.send(toAddress, msg);
//		Log.d("PingThread","NetworkController-sendPingReply to: "+toAddress.toString());
//		return true;
//	}
	public static boolean sendVersion(Address toAddress, long data){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		Payload p=new Payload();
		p.addParam(Protocol.TREE_VERSION, data+"");
		Log.d("An","NetworkController-sendVersion : "+ data);
		msg.setPayload(p);
		msg.setType(Protocol.TREE_VERSION);
		_peer.send(toAddress, msg);
//		Log.d("An","sendTreeText to: "+toAddress.toString());
		return true;
	}
	
	public static boolean sendGetVersion(Address toAddress){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType("GET_VERSION");
		_peer.send(toAddress, msg);
		Log.d("An","NetworkController-sendGetVersion to: "+toAddress.toString());
		return true;
	}
	public static boolean sendVersionTree(String toAddress, long version){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		Payload p = new Payload();
		p.addParam("VERSION", version+"");
		msg.setPayload(p);
		msg.setType("SEND_VERSION");
		_peer.send(new Address(toAddress), msg);
		Log.d("An","NetworkController-sendVersionTree to: "+toAddress.toString()+" version: "+version);
		return true;
	}
	public static boolean sendResultNode(Address toAddress, String list, String delList ){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		Payload p = new Payload();
		p.addParam("LIST", list+"");
		p.addParam("DELLIST", delList+"");
		msg.setPayload(p);
		msg.setType("RESULT_NODE");
		_peer.send(toAddress, msg);
		Log.d("An","NetworkController-sendResultNode to: "+toAddress.toString());
		return true;
	}
	
	//end phu
	// ========================================truc===============================================

	public static void ShowMessageNoticeTAB(final String message) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				ActivityController.ShowMessageTAB(message);
			}
		});
	}
	// chat rieng
	public static void set_isOffline(boolean _isOffline) {
		NetworkController._isOffline = _isOffline;
	}

	public static boolean isOffline() {
		return _isOffline;
	}

	public static void set_ipHost(String _ipHost) {
		NetworkController._ipHost = _ipHost;
	}

	public static String get_ipHost() {
		return _ipHost;
	}

	public static void set_ipUser(String _ipUser) {
		NetworkController._ipUser = _ipUser;
	}

	public static String get_ipUser() {
		return _ipUser;
	}

	public static void peerRelease() {
		_peer.halt();
	}

	public static void set_fullName(String _fullName) {
		NetworkController._fullName = _fullName;
	}

	public static String get_fullName() {
		return _fullName;
	}

	public static void set_userName(String _userName) {
		NetworkController._userName = _userName;
	}

	public static String get_userName() {
		return _userName;
	}

	public static void init_runnableUpdateMsg() {
		// install runnable
		_runUpdateMsg = new Runnable() {
			@Override
			public void run() {

				frmChatPeerActivity.updateMessage();
			}
		};
	}

	public static void ShowChatPeer(final String ipSender, final String userName) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowChatPeer(ipSender, userName);
			}
		});
	}

	public static void ShowChatPeerNonParamater() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowChatPeerNonParamater();
			}
		});
	}

	public static void UpdateMessageInConversation(String keychat, String mess, String ip) {
		final ArrayList<Object> message = new ArrayList<Object>();
		message.add(keychat);
		message.add(mess);
		// message.add(type);
		message.add(ip);
		// message.add(fullName);
		ActivityController.hander.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// frmMyConversation.receiveMessage(message);
			}
		});
	}

	public static void SendChatMessagePeer(Address addr, String message) {
		_peer.SendChatPeerMessage(addr, message);
	}

	public static void SendMessageLogout() {
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				ArrayList<String> ipList = ReadXML.ReadIP(ReadWriteFileController.pathNeighborsList);
				for (String ip : ipList)
					_peer.SendMessageLogout(new Address(ip));
				NetworkController.peerRelease();
				Log.d("PEERDROID", "tat peer");
				ReadWriteFileController.deleteFile(ReadWriteFileController.pathNeighborsList);
				// xoá tất cả nội dung tin nhắn group:
				ReadWriteFileController.deleteFolder(ReadWriteFileController.DIRECTORYCHATPEER);
				Log.d("PEERDROID", "Đã Thoát khỏi chương trình");
				System.exit(0);
				// Thread.currentThread().interrupt();

			}
		});
		t.start();
	}

	private static String getMessage(String[] temp) {
		String result = "";
		// i chay tu 2 đe lay ra message
		for (int i = 2; i < temp.length; i++) {
			if (i == temp.length - 1) {
				result = result + temp[i];
			} else {
				result = result + temp[i] + "/";
			}
		}
		return result;
	}

	public static void ReceiveMessageChatPeer(JSONObject params, Address sender) throws IOException {
		Log.d("Phu", "vao ReceiveMessageChatPeer");
		if (_peer.getAccount().getRuleById(7) != null && _peer.getAccount().getRuleById(7).getReceive()) {
			Iterator<String> iter = params.keys();
			while (iter.hasNext()) {
				Log.d("Phu", "vao while ReceiveMessageChatPeer");
				String key = iter.next();
				String s = null;
				try {
					s = params.get(key).toString();
					// username/text/ip
					Log.d("Phu", "s=" + s);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Log.d("Phu", "Key " + key);
				if (key.equals("Message")) {
					Log.d("Phu", "key la " + key);
					String[] sTemp = s.split("/");
					final String acc = sTemp[0];
					final String ipsend = sTemp[2];
					String mess = sTemp[1];// getMessage(sTemp);
					Log.d("Phu", "controller username: " + acc);
					Log.d("Phu", "controller ip send: " + ipsend);
					Log.d("Phu", "Sender ip=" + sender.getURL());
					Log.d("Phu", "controller mess: " + mess);
					// ---------tien hanh ghi file----------

					// ReadWriteFileController.writeTXT("Peer_"+acc+"_Content.txt",
					// fullName + ":" + mess);
					ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATPEER + "Peer_" + acc
							+ "_Content.txt", acc + ":" + mess);
					Log.d("Phu", "da ghi file xong");

					String userNameChatting = frmChatPeerActivity._FriendChatting;
					Log.d("Phu", "=====================username dang chat=" + userNameChatting);

					if (userNameChatting == null) {
						frmChatPeerActivity._FriendChatting = acc;
						ShowChatPeer(ipsend, acc);
					} else {
						Log.d("Phu", "----------Acc = " + acc);
						Log.d("Phu", "----------chatting = " + userNameChatting);
						if (userNameChatting.equals(acc)) {// la dang chat voi
															// minh
							Log.d("Phu", "dang chat together");
							handler.post(_runUpdateMsg);
							// init_runnableUpdateMsg();
							// handler.post(frmChatPeerActivity._runUpdateMsg);
							Log.d("Phu", "run update message xong");
						} else {// minh dang chat voi nguoi khac
							Log.d("Phu", "dang chat voi nguoi khac");
							// show notification co sender gui tin nhan
							NotificationController.sendNotification(ActivityController.getPeerActivity()
									.getBaseContext(), frmChatPeerActivity.class, "Nhận tin nhắn của " + acc, mess,
									Notification.DEFAULT_SOUND, acc, ipsend);
						}
					}
					// chay wa rui ok

					Log.d("Phu", "networkcontroller vao conversation nhan tin nhan");
					// ActivityController.hander.post(new Runnable() {
					//
					// @Override
					// public void run() {
					// // TODO Auto-generated method stub
					// frmConversation.receiveMessage(message);
					// }
					// });

					// frmMyConversation.mess=message;
					// handler.post(frmMyConversation.raReceiveMessage);

					Log.d("Phu", "conversation nhan tin nhan xong");
				}
			}
		} else {
			Log.d("Phu", "gui phan hoi ko chat net layer");
			NetworkController.ShowMessageNotice("Bạn không có quyền nhận tin nhắn trò chuyện.");
			NetworkController.GuiPhanHoiKhongCoQuyenChat(sender, _peer.getAccount().get_Username());
		}
	}

	public static void ShowChatConversation() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowChatConversation();
			}
		});
	}

	// ====end chat rieng

	// tao lao==========

	public static void SendHelloDLG(Address toAdd) {
		PingMessage m = new PingMessage(_peer.getPeerDescriptor());
		m.setType(Protocol.HELLO);
		_peer.send(toAdd, m);

	}

	public static void ShowForm1() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowFrm1();
			}
		});
	}

	public static void ShowForm2() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowFrm2();
			}
		});
	}

	// tao lao================

	// Quyền : 0:Chat, 1:Cam ngkhac noi, 2: moi nguoi khac ra khoi nhom
	public static void ShowMessageNotice(final String message) {
//		handler.post(new Runnable() {
//
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub

				ActivityController.ShowMessage(message);
//			}
//		});
	}

	public static void ShowMessageChat(final String content, final String Address) {
//		handler.post(new Runnable() {
//			@Override
//			public void run() {
//				ActivityController.ShowChatMessage(content, Address);
//			}
//		});
		trucActivity.chatMessage=content;
		trucActivity.addressFriend=Address;
		handler.post(trucActivity.showChatMessage);
	}

	public static void HienThiTinNhanChatRieng() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				// ActivityController.HienThiTinNhanChatRieng();
			}
		});
	}

	public static void DislayVoteKickMember() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.DislayKickMember();
			}
		});
	}

	public static void DislayResultVoteKick() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowResultVote();
			}
		});
	}

	public static void doEndTimeKick() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.DoEndTime();
			}
		});
	}

	// quyen 6
	public static void GuiYeuCauNgungThaoLuan(final Address toAdd, int time) {
		Log.d("Phu", "vao Controller ngung noi");

		
		PingMessage mess = new PingMessage(_peer.getPeerDescriptor());
		mess.setType(Protocol.STOP_TALKING_ONE_MEMBER);
		Payload pl = new Payload();
		pl.addParam("TimeStopTalk", time);
		mess.setPayload(pl);
		// String message="Ban da bi ngung noi";
		_peer.send(new Address(toAdd), mess);

		Log.d("Phu", "gui yeu cau ngung noi");
	}

	public static void GuiChoPhepThaoLuan(Address toAddress) {
		Log.d("Phu", "vao Controller cho phep noi");
		// boolean YourRule = _peer.getAccount().getRuleById(6).getSend();
		// if (YourRule) {
		Log.d("Phu", "vao if cho noi");
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.ACCEPT_TALKING_ONE_MEMBER);
		_peer.send(new Address(toAddress), message);
		Log.d("Phu", "gui yeu cau cho noi");
		// } else {
		// Log.d("Phu", "ko get dc quyen");
		// NetworkController.ShowMessageNotice(Protocol.NON_RULE_MESSAGE);
		// }
	}

	public static void NhanYeuCauNgungThaoLuan(JSONObject params, Address address) throws NumberFormatException,
			JSONException {
		// quyen thao luan =false==4 //tam thoi la quyen chat rieng=7
		if (_peer.getAccount().getRuleById(4) != null) {
			_peer.getAccount().getRuleById(4).setSend(false);
			Iterator<String> listKey = params.keys();
			String key;
			int time = 0;
			while (listKey.hasNext()) {
				Log.d("Phu", "vao while");
				key = listKey.next();
				String s = null;
				try {
					s = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (key.equals("TimeStopTalk")) {
					time = Integer.parseInt(s);
				}

			}
			Log.d("Phu", "moi sua: Send " + _peer.getAccount().getRuleById(7).getSend());
			String s = Protocol.STOP_TALKING_MESSAGE + " trong vòng " + time + " giây. Vui lòng chờ.";
			NetworkController.ShowMessageNotice(s);
		}
	}

	public static void NhanChoPhepThaoLuan() {
		if (_peer.getAccount().getRuleById(4) != null) {
			_peer.getAccount().getRuleById(4).setSend(true);
			Log.d("Phu", "Da sua lai wuyen noi" + _peer.getAccount().getRuleById(7).getSend());
			NetworkController.ShowMessageNotice(Protocol.ACCEPT_TALKING_MESSAGE);
		}
	}

	// Quyen 7
	public static void GuiTinNhanChat(Address toAddress, String content) {

		PingMessage mess = new PingMessage(_peer.getPeerDescriptor());
		mess.setType(Protocol.CHAT_MESSAGE);
		Payload pl = new Payload();
		pl.addParam("Content_Chat", content);
		mess.setPayload(pl);
		_peer.send(new Address(toAddress), mess);
		Log.d("Phu", "GuiTinNhanChat to" + toAddress.toString());
	}

	public static void GuiPhanHoiKhongCoQuyenChat(Address toAddress, String username) {
		Log.d("Phu", "gui phan hoi ko co quyen chat");
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.CHAT_FEEDBACK_NON_RULE);
		Payload pl = new Payload();
		pl.addParam("Content", username + " không có quyền nhận tin nhắn trò chuyện.");
		message.setPayload(pl);
		_peer.send(new Address(toAddress), message);
	}

	public static void NhanPhanHoiKhongCoQuyenTroChuyenRieng(JSONObject params, Address address)
			throws NumberFormatException, JSONException {
		String key;

		Iterator<String> listKey = params.keys();
		while (listKey.hasNext()) {
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("Content")) {

				NetworkController.ShowMessageNotice(s);
			}
		}

	}

	public static void NhanTinNhanTroChuyenRieng(JSONObject params, Address address) throws NumberFormatException,
			JSONException {
		String key;
		if (_peer.getAccount().getRuleById(7) != null && _peer.getAccount().getRuleById(7).getReceive()) {
			Iterator<String> listKey = params.keys();
			while (listKey.hasNext()) {
				key = listKey.next();
				String s = null;
				try {
					s = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (key.equals("Content_Chat")) {

					// frmChatPeerActivity.arrMessage.add(s);
					// frmChatPeerActivity.myFriend = sender;
					// NetworkController.ShowChatPeer();
					// NetworkController.HienThiTinNhanChatRieng();
					Log.d("Phu", "Da show noi dung chat nhan dc");
				}
			}
		} else {
			Log.d("Phu", "gui phan hoi ko chat net layer");
			NetworkController.ShowMessageNotice("Bạn không có quyền nhận tin nhắn trò chuyện.");
			// NetworkController.GuiPhanHoiKhongCoQuyenChat(address);
		}
	}

	// Quyen 4 thao luan
	public static void NhanTinNhanThaoLuan(JSONObject params, Address address) throws NumberFormatException,
			JSONException {
		String key;
		Quyen quyen = _peer.getAccount().getRuleById(4);
		if (quyen != null && quyen.getReceive()) {
			Iterator<String> listKey = params.keys();
			while (listKey.hasNext()) {
				key = listKey.next();
				String s = null;
				try {
					s = params.get(key).toString();
				} catch (JSONException e) {
					Log.d("Phu", "Lỗi trong hàm NhanTinNhanThaoLuan: " + address.toString());
					e.printStackTrace();
				}
				if (key.equals("Content_Chat")) {
					NetworkController.ShowMessageChat(s, address.getURL());
					Log.d("Phu", "NhanTinNhanThaoLuan từ: " + address.toString());
				}
			}
		} else {
			Log.d("Phu", "Không có quyền NhanTinNhanThaoLuan");
			Log.d("Phu", quyen.toString());
			// NetworkController.ShowMessageNotice("Bạn không có quyền nhận tin nhắn trò chuyện.");
			// NetworkController.GuiPhanHoiKhongCoQuyenChat(address);
		}
	}

	// ========Quyen 5
	// gửi thông báo cần biểu quyết để mời 1 thành viên ra khỏi nhóm
	public static void SendVoteKickMember(Address toAddress, Address beingKick, int time) {
		Log.d("Phu", "vao send vote");
		Log.d("Phu", "being ip = " + beingKick.toString());
		ArrayList<CMember> memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
		Log.d("Phu", "size = " + memberList.size());
		String ipPort = "sip:" + beingKick.getURL();
		Log.d("Phu", "ip being gan= " + ipPort);
		CMember ipMember = new CMember();
		for (CMember m : memberList) {
			Log.d("Phu", "ip = " + m.get_ip());
			if (m.get_ip().equals(beingKick.toString())) {
				ipMember = m;
				break;
			}

		}
		if (ipMember != null) {
			Log.d("Phu", "member" + ipMember.get_userName());
			Log.d("Phu", "vao if send vote");
			PingMessage message = new PingMessage(_peer.getPeerDescriptor());
			message.setType(Protocol.KICK_MEMBER_OUT_MESSAGE);
			Payload pl = new Payload();

			pl.addParam("Time", time);
			pl.addParam("IPBeingKick", beingKick.getURL());
			pl.addParam("UserNameBeing", ipMember.get_userName());

			Log.d("Phu", "ip bi kick " + beingKick.getURL());
			message.setPayload(pl);
			_peer.send(toAddress, message);
			Log.d("Phu", "da send vote");
		}
	}
	
	//truyen vao ca username nguoi bi kick
	public static void SendVoteKickMemberGroup(String userName, Address beingKick, int time) {
		Log.d("Phu", "vao send vote");
		Log.d("Phu", "being ip = " + beingKick.toString());
		ArrayList<CMember> memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
		Log.d("Phu", "size = " + memberList.size());
		String ipPort = "sip:" + beingKick.getURL();
		Log.d("Phu", "ip being gan= " + ipPort);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.KICK_MEMBER_OUT_MESSAGE);
		Payload pl = new Payload();

		pl.addParam("Time", time);
		pl.addParam("IPBeingKick", beingKick.getURL());
		pl.addParam("UserNameBeing", userName);

		Log.d("Phu", "ip bi kick " + beingKick.getURL());
		message.setPayload(pl);
		CMember ipMember = new CMember();
		for (CMember m : memberList) {
			Log.d("Phu", "ip = " + m.get_ip());
			_peer.send(new Address(m.get_ip()), message);
		}
	}

	// gửi ý kiến biểu quyết về việc mời 1 thành viên ra khỏi nhóm
	public static void SendFedbackKickMember(Address toAddress, int vote) {
		Log.d("Phu", "vao ham bieu quyet kick");
		// int vote=frmBieuQuyetMoiRoiNhom.YKienBieuQuyet;
		Log.d("Phu", "bieu quyet kick = " + vote);
		// Quyen myRule = _peer.getAccount().getRuleById(13);
		// if (myRule != null && myRule.getSend()) {
		Log.d("Phu", "vao if bieu quyet kick");
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.KICK_MEMBER_OUT_FEEDBACK);
		Payload pl = new Payload();
		if (vote == 1) {
			Log.d("Phu", " bieu quyet kick = yes");
			pl.addParam("VOTE", "1");
		} else if (vote == 0) {
			Log.d("Phu", " bieu quyet kick = no");
			pl.addParam("VOTE", "0");
		} else {
			Log.d("Phu", " bieu quyet kick = khac");
		}
		message.setPayload(pl);
		_peer.send(toAddress, message);
		// } else {

		// NetworkController.ShowMessageNotice("bạn không có quyền biểu quyết kick");
		// Log.d("Phu", "ko co quyen bieu quyet kick");
		// }
	}

	// hàm gửi kết quả cuoi cung ve moi nguoi khac ra khoi nhom
	public static void SendResultVoteKickMember(Address toAdd, int result, Address beingKickAdd) {
		Log.d("Phu", "vao ham SendResultVoteKickMember");

		Log.d("Phu", "vao if send result kick");
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.KICK_MEMBER_OUT_RESULT);
		Payload pl = new Payload();

		pl.addParam("Result", result);
		pl.addParam("BeingKick", beingKickAdd.getURL());
		message.setPayload(pl);
		_peer.send(toAdd, message);
		Log.d("Phu", "da send result kick");

	}

	public static void ReceiveVoteKickMember(JSONObject params, Address address) throws NumberFormatException,
			JSONException {
		Log.d("Phu", "Vao ReceiveVoteKickMember");

		
		frmBieuQuyetMoiRoiNhom.senderKick = address;
		// NetworkController.ShowMessageNotice("da nhan dc tin nhan Kick");
		// ActivityController.ShowMessage("nhan dc");
		String key;
		int time = 0;
		String ipBeingKick = "";
		String ip = _peer.getAddressPeer();
		Log.d("Phu", "my ip " + ip);
		Iterator<String> listKey = params.keys();
		String userNameBeingKick = "";
		while (listKey.hasNext()) {
			Log.d("Phu", "vao while");
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("Time")) {
				Log.d("Phu", "key = time");
				Log.d("Phu", "s =" + s);
				time = Integer.parseInt(s);
				Log.d("Phu", "time=" + time);
			}
			if (key.equals("IPBeingKick")) {
				Log.d("Phu", "key = being kick ip");
				ipBeingKick = s;
				Log.d("Phu", "being kick ip=" + ipBeingKick);
			}
			if (key.equals("UserNameBeing")) {
				userNameBeingKick = s;
			}
		}
		Log.d("Phu", "ra khoi while");

		// NetworkController.SetTimeKick(time);

		// có viết hàm thông qua các class controller va activitycontroller
		// nhung ko thanh cong nen gan truc tiep
		Log.d("Phu", "settime kick");
		Log.d("Phu", "time to vote = " + time);
		Quyen myRule = _peer.getAccount().getRuleById(13);
		if (myRule != null && myRule.getSend()) {//co quyen bieu quyet
			if (ip.equals(ipBeingKick) == false) {
				Log.d("Phu", "ko khop ip trong send vote");
				frmBieuQuyetMoiRoiNhom.timeVoteKick = time;
				frmBieuQuyetMoiRoiNhom.beingKickUserName = userNameBeingKick;
				NetworkController.DislayVoteKickMember();
				return;
			}
		}
		Log.d("Phu", "la nguoi bi kick");
//		NetworkController.ShowMessageNotice("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		NetworkController.ShowMessageNoticeTAB("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		// set tat ca cac quyen cua nguoi nay la false.
		// ko cho chat rieng
		NetworkController._peer.getAccount().getRuleById(7).setSend(false);
		// ko cho thao luan
		NetworkController._peer.getAccount().getRuleById(4).setSend(false);
		// ko cho bieu quyet
		NetworkController._peer.getAccount().getRuleById(8).setSend(false);
		// ko cho Chia sẻ tài liệu (Up tài liệu)
		NetworkController._peer.getAccount().getRuleById(9).setSend(false);
		// ko cho Tải tài liệu
		NetworkController._peer.getAccount().getRuleById(10).setSend(false);
		// ko cho xóa tài liệu
		NetworkController._peer.getAccount().getRuleById(11).setSend(false);
		// ko cho Biểu quyết
		NetworkController._peer.getAccount().getRuleById(13).setSend(false);
		// ko cho Đánh giá bản thân và người khác
		NetworkController._peer.getAccount().getRuleById(15).setSend(false);

		// phai phong truong hop no nhan duoc thong bao nay tu nhien roi
		// khoi nhom.ko cho quyet dinh.
		Log.d("Phu", "Da show thong bao ");
	}

	public static void ReceiveFeedbackKickMember(JSONObject params) throws NumberFormatException, JSONException {
		String key;
		Iterator<String> listKey = params.keys();
		while (listKey.hasNext()) {
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("VOTE")) {
				Log.d("Phu", "lay vote");
				if (s.equals("1")) {
					tabActivity.yesVote.add(1);
				} else if (s.equals("0")) {
					tabActivity.noVote.add(1);
				}
			}
		}
	}

	public static void ReceiveResultKickMember(JSONObject params) throws NumberFormatException, JSONException {
		String key;
		int kq = -1;

		Iterator<String> listKey = params.keys();
		String myIP = _peer.getAddressPeer();
		Log.d("Phu", "my IP=" + myIP);
		String ipBeingKick = "";
		while (listKey.hasNext()) {
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("Result")) {
				Log.d("Phu", "lay ket qua cuoi cung");
				if (s.equals("1")) {
					// NetworkController.ShowMessageNotice("Thành viên trên đã bị mời khỏi nhóm");
					kq = 1;
				} else if (s.equals("0")) {
					kq = 0;
					// NetworkController.ShowMessageNotice("Mời thành viên khỏi nhóm đã thất bại.");
				}
				Log.d("Phu", "ket qua cuoi cung = " + s);
			}
			if (key.equals("BeingKick")) {
				Log.d("Phu", "lay ip bi kick result");
				Log.d("Phu", "ip bi kick result : " + s);
				ipBeingKick = s;
				// Log.d("Phu","My ip result : "+myIP.getURL());
			}
		}
		ArrayList<CMember> memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
		String ipPort = "sip:" + ipBeingKick;
		CMember ipMember = new CMember();
		for (CMember m : memberList) {
			if (m.get_ip().equals(ipPort)) {
				ipMember = m;
				break;
			}

		}
		if (ipBeingKick.equals(myIP)) {
			Log.d("Phu", "khop ip bi kick result");
			if (kq == 1) {
				Log.d("Phu", "kq bi kick result =1 ");
				NetworkController.ShowMessageKicked();
				// xoa nguoi nay khoi danh sach nhom

			} else {
				Log.d("Phu", "kq bi kick result =0 ");
				//NetworkController.ShowMessageNotice("Mời bạn rời khỏi nhóm đã thất bại.");
				NetworkController.ShowMessageNoticeTAB("Mời bạn rời khỏi nhóm đã thất bại.");
			}
		} else {
			Log.d("Phu", "ko khop ip bi kick result");
			if (kq == 1) {
				Log.d("Phu", "kq bi kick result =1 ");
				String s = "";
				s += ipMember.get_userName() + " đã bị mời ra khỏi nhóm.";
			//	NetworkController.ShowMessageNotice(s);
				NetworkController.ShowMessageNoticeTAB(s);
			} else {
				Log.d("Phu", "kq bi kick result =0 ");
				//NetworkController.ShowMessageNotice("Mời thành viên khỏi nhóm đã thất bại.");
				NetworkController.ShowMessageNoticeTAB("Mời thành viên khỏi nhóm đã thất bại.");
			}

		}
	}

	public static void ShowMessageKicked() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowMessageKicked();
			}
		});
	}

	public static void CloseDiscussActivity() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.FinishDiscussActivity();
			}
		});
	}

	public static void CloseChatPeerActivity() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				 ActivityController.FinishChatPeerActivity();
			}
		});
	}

	// =====end truc==================================================

	public static void init(String name, int port, AccountDTO account) {
		Log.d("Phu", " NetworkController init ");
		_peer = new NetworkLayer(null, "4654amv65d4as4d65a4", name, port, account);
		
	}
	
	//**************
	// ----An
	//**************
	
	// Ham Send Group Sign Out
	public static void sendGroupSignOut(String toAddress, String name) {
		Log.d("PEERDROID", "da nhan duoc name sign out." + name);
		Payload p = new Payload();
		p.addParam("NAME", name);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.GROUP_SIGN_OUT);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send group sign out...");
	
	}

	// Ham Send Group Danh Gia
	public static void sendGroupDanhGia(String toAddress) {
		
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.GROUP_DANH_GIA);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send group danh gia..");
		
	}

	// Ham Send Result Danh Gia
	public static void sendResultDanhGia(String toAddress, String result) {
		
		Payload p = new Payload();
		p.addParam("RESULT", result);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.RESULT_DANH_GIA);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send result danh gia...");
		
	}

	// Ham Send Group Bieu Quyet
	public static void sendGroupBieuQuyet(String toAddress, int index, String title) {
		
		Payload p = new Payload();
		p.addParam("INDEX", index);
		p.addParam("TITLE", title);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.GROUP_BIEU_QUYET);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send group bieu quyet...");
		
	}

	// Ham Send Result Bieu Quyet
	public static void sendResultBieuQuyet(String toAddress, int index, int value) {
		
		Payload p = new Payload();
		p.addParam("INDEX", index);
		p.addParam("VALUE", value);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.RESULT_BIEU_QUYET);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send ket qua bieu quyet...");
	
	}

	// Ham Send Text Log
	public static void sendTextLog(String toAddress, String text, String name) {
		Payload p = new Payload();
		p.addParam("TEXT", text);
		p.addParam("NAME", name);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.LOG_FILE);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send text log...");
	
	}
	
//	public static void sendAddTextNode(Address toAddress,long parentID, INodeText node) {
//		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
//		Payload payload = new Payload();
//		payload.addParam("TEXT_NODE", node.toParse());
//		payload.addParam("TEXT_NODE_ID", parentID+"");
//		msg.setType(Protocol.ADD_TEXT_NODE);
//		msg.setPayload(payload);
//		_peer.send(toAddress, msg);
//		Log.d("An", "Da send sendAddTextNode to: " + toAddress.toString()+" parentID= "+parentID);
//		
//	}
	// ***************************
	//
	// ------ Cac Ham Receive ----
	//
	// ***************************

	// Receive Result Danh gia
	public static void ReceiveDanhGia(JSONObject params, final Address sender) {
		Log.d("PEERDROID", "vao ham ReceiveDanhGia");
		
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowDanhGia(sender);
			}
		});
	}
	// Receive Bieu Quyet
	public static void ReceiveBieuQuyet(JSONObject params, final Address sender) {

		Iterator<String> iter = params.keys();
		final int index;
		int i = 0;
		final String title;
		String str = "";
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("INDEX")) {

				i = Integer.valueOf(s);
			}
			if(key.equals("TITLE")){
				str = s;
			}
		}
		// frmBieuQuyetActivity.timeVote = time;
		title = str;
		index = i;
		Log.d("PEERDROID", "title " + title);
		Log.d("PEERDROID", "index " + index);
		ActivityController.hander.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("PEERDROID", "vao handler..........");
				trucActivity.showNotificationBieuQuyet(index, sender,title);
			}
		});
		Log.d("PEERDROID", "vao ham ReceiveBieuQuyet");
	}

	// Receive Result Danh gia
	public static void ReceiveResultDanhGia(JSONObject params, final Address sender) {
		Log.d("PEERDROID", "vao ham ReceiveResultDanhGia");
		Iterator<String> iter = params.keys();
		final String result;
		String str = "";
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("RESULT")) {
				str = s;
			}
		}
		result = str;
		Log.d("PEERDROID", "Ket qua: " + result);
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.CountResultDanhGia(result);
			}
		});
	}

	// Ham receive Result Bieu Quyet
	public static void ReceiveResultBieuQuyet(JSONObject params, final Address sender) {
		Log.d("PEERDROID", "vao ham ReceiveResultDanhGia");
		Iterator<String> iter = params.keys();
		final int index;
		final int value;
		int in = 0;
		int va = 0;
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("INDEX")) {
				Log.d("PEERDROID", "index: " + s);
				in = Integer.parseInt(s);
			}
			if (key.equals("VALUE")) {
				Log.d("PEERDROID", "value: " + s);
				va = Integer.parseInt(s);
			}
		}
		index = in;
		value = va;
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.CountResultBieuQuyet(index, value);
			}
		});
	}
	
	// Ham receive Sign Out
	public static void ReceiveSignOut(JSONObject params, final Address sender){
		Log.d("PEERDROID", "vao ham ReceiveSignOut");
		Iterator<String> iter = params.keys();
		final String name;
		String n = "";
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}if(key.equals("NAME")){
				n = s;
			}
		}
		name = n;
		Log.d("PEERDROID", "name sign out da nhan: " + name);
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowSignOut(name);
			}
		});
	}
	
	// Ham receive Text Log
	public static void ReceiveTextLog(JSONObject params, final Address sender){
		boolean isTrue = _peer.account.isThanhLapNhom; 
		if(isTrue == true){
			Log.d("PEERDROID", "vao ham ReceiveTextLog");
			Iterator<String> iter = params.keys();
			final String Text;
			final String Name;
			String t = "";
			String n = "";
			while (iter.hasNext()) {
	
				String key = iter.next();
				String s = null;
				try {
					s = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}if(key.equals("TEXT")){
					t = s;
				}if(key.equals("NAME")){
					n = s;
				}
			}
			Text = t;
			Name = n;
			Log.d("PEERDROID", "Tex log da nhan: " + Name + Text);
			handler.post(new Runnable() {
	
				@Override
				public void run() {
					// TODO Auto-generated method stub
					ActivityController.WriteTextToLog(Text,Name);
				}
			});
		}
		else{
			Log.d("PEERDROID", "ko co quyen nhan text Log" );
		}
	}
	//***********************
	//---end An
	//**********************
	/**
	 * Đặt lại vai trò cho account<br>
	 * 1.Reset role<br>
	 * 2.Đọc role từ file lên
	 */
	public static boolean resetRole() {
		Log.d("Phu", "NetworkController reset Role");
		_peer.account.resetRole();
		ArrayList<RoleDTO> roleList = ReadWriteFileController.readRole(null,ReadWriteFileController.MY_ROLE_PATH);
		for (RoleDTO role : roleList) {
			_peer.account.addRole(role);
			Log.d("Phu", "Role name: " + role.getName());
		}
		if(roleList.size()==0)
			return false;
		return true;
	}

	public static boolean getIsThanhLapNhom() {
		return _peer.account.isThanhLapNhom;
	}

	/**
	 * Lấy 2(3) số cuối của địa chỉ IP Phục vụ cho việc định danh node trong cây
	 * thảo luận
	 * 
	 * @return
	 */
	public static long getPersonID() {
		nodeCurrenIndex++;
		String s = _peer.getSimpleIP();
		String[] m = s.split("\\.");
		return Integer.parseInt(m[3]) * 1000 + System.currentTimeMillis();
	}
	public static synchronized boolean getStated(){
		return isConnected;
	}
	public static synchronized void setStated(boolean conneted){
		isConnected=conneted;
	}
	
	
	
}
